<?php

namespace Yj\Crontab;

use Hyperf\Crontab\Event\CrontabDispatcherStarted;
use Hyperf\Crontab\Strategy\StrategyInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\ProcessManager;

class CrontabProcess extends AbstractProcess
{
    public $name = 'yj crontab';

    /**
     * @Inject()
     * @var CrontabStrategy
     */
    private $strategy;

    /**
     * @Inject()
     * @var CrontabScheduler
     */
    private $scheduler;

    public function handle(): void
    {
        while (ProcessManager::isRunning()){
            $this->sleep();
            $crontabs = $this->scheduler->schedule();
            while (!$crontabs->isEmpty()) {
                /**
                 * @var Crontab  $crontab
                 */
                $crontab =  $crontabs->dequeue();
                $this->strategy->dispatch($crontab);
            }
        }
    }

    private function sleep()
    {
        $current = date('s', time());
        $sleep = 60 - $current;
        dump('hyperf-cmf Crontab dispatcher sleep ' . $sleep . 's.');
        $sleep > 0 && \Swoole\Coroutine::sleep($sleep);
    }


}